﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class MainPanelManager : MonoBehaviour
{
	private GameObject introduction;
	private GameObject selectPanel;
	private GameObject title;
	private Vector3 startPos;
	[SerializeField]
	private Vector3 endPos;

	private Text introduction_text;
	private Text title_text;

	//文字的Alpha值
	private float alpha = 1;

	//
	private bool isStarted = false;
	private bool isFirstPage = false;

	private void Awake()
	{
		selectPanel = transform.Find("SelectPanel").gameObject;
		introduction = transform.Find("Introduction").gameObject;
		introduction_text = introduction.GetComponent<Text>();
		title = transform.Find("Title").gameObject;
		startPos = title.transform.localPosition;
	}

	// Update is called once per frame
	void Update()
	{
		SetAlpha(introduction_text, alpha);
		if (Input.anyKeyDown && isStarted == false)
		{
			PreStartGame();
			MoveTitle(true);
		}
		if (alpha < 0.05f && isStarted == false)
		{
			StartGame();
		}
		if (Input.GetKeyDown(KeyCode.Escape))
		{
			if (!isFirstPage)
			{
				Esc();
			}
			else
			{
				Debug.Log("Quit");
				Application.Quit();
			}
		}
		else if (Input.GetKeyDown(KeyCode.Alpha1) || Input.GetKeyDown(KeyCode.Alpha2) || Input.GetKeyDown(KeyCode.Alpha3) || Input.GetKeyDown(KeyCode.Alpha4))
		{
			isFirstPage = false;
			//MoveTitle(isFirstPage);
		}
	}

	void MoveTitle(bool isFirstPage)
    {
		if (isFirstPage)
			StartCoroutine(MoveTitleCoroutine(startPos,endPos));
		//else
		//	StartCoroutine(MoveTitleCoroutine(endPos, startPos));
	}

	private IEnumerator MoveTitleCoroutine(Vector3 startPos, Vector3 endPos)
    {
	    title.transform.localPosition = startPos;
	    float speed = -1000f;
		//第二段运动
		while (Vector3.Distance(title.transform.localPosition, endPos) > 1e-6)
		{
			title.transform.localPosition = Vector3.MoveTowards(title.transform.localPosition, endPos, speed * Time.deltaTime);
			speed += 5000 * Time.deltaTime;
			yield return null;
		}
		
    }

	void PreStartGame()
    {
	    StartCoroutine(FSetAlpha(1, 0));
    }
	void StartGame()
	{		
		isStarted = true;
		selectPanel.SetActive(true);
		isFirstPage = true;
	}

	void SetAlpha(Text text, float alpha)
	{
		Color color = text.color;
		color.a = alpha;
		text.color = color;
	}

	private IEnumerator FSetAlpha(float start,float end)
    {
		float tmpAlpha = start;
		if(alpha > end)
			while(tmpAlpha　>= end)
			{
				tmpAlpha -= Time.deltaTime;
				alpha = tmpAlpha;
				yield return null;
			}
    }

	private void Esc()
    {
		SelectPanel ui = selectPanel.GetComponent<SelectPanel>();
		ui.OpenPanel(ui.transform.Find("RootPanel").gameObject);
		isFirstPage = true;
	}		

}
